package person.learn.restful;

import org.json.JSONObject;
import org.junit.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created by barton on 16-4-19.
 */
//@RunWith(SpringJUnit4ClassRunner.class)
//@SpringApplicationConfiguration(classes = SpringBootLearnApplication.class)
//@WebAppConfiguration
public class RestFulTestCase/* extends BaseTest */ {

    private RestTemplate restTemplate = new RestTemplate();
//    private Log log = LogFactory.getLog(RestFulTest.class);

    // 第一种方式:直接返回list
//[
//    {
//        "name": "Apple",
//        "shape": "circle"
//    },
//    {
//        "name": "Orange",
//        "shape": "circle"
//    }
//]
    // 第二种方式:返回JSONObject
//{
//    "fruits": [
//            {
//                "name": "Apple",
//                "shape": "circle"
//            },
//            {
//                "name": "Orange",
//                "shape": "circle"
//            }
//        ]
//}
//    @Test
//    public void testGetList1() throws Exception {
//        MockHttpServletResponse msr = doGet("/v1/fruits");
//        Assert.assertEquals(200, msr.getStatus());
//
////        log.info(msr.getContentAsString());
//        System.out.println(msr.getContentAsString());
//    }

    @Test
    public void testGetList2() throws Exception {
        // 使用JSONObject作为返回类型时 需要使用String进行接收.
//        ResponseEntity<String> responseEntity = restTemplate.getForEntity
//                ("http://localhost:8443/v1/fruits", String.class, "");
//        System.out.println(responseEntity.getStatusCode());
//        System.out.println(responseEntity.getBody());
//        System.out.println(responseEntity.getHeaders());

//        ResponseEntity<List> responseEntity = restTemplate.getForEntity
//                ("http://localhost:8443/v1/fruits", List.class, "");
//        System.out.println(responseEntity.getStatusCode());
//        System.out.println(responseEntity.getBody());
//        System.out.println(responseEntity.getHeaders());

//        Fruit[] list = restTemplate.getForObject("http://localhost:8443/v1/fruits", Fruit[]
// .class);
//        for (Fruit fruit : list) {
//            System.out.println(fruit.getName());
//            System.out.println(fruit.getShape());
//        }

        List<Fruit> list = restTemplate.exchange("http://localhost:8443/v1/fruits", HttpMethod
                .GET, null, new ParameterizedTypeReference<List<Fruit>>() {
        }).getBody();

        list.forEach(l -> {
            System.out.println(l.getName());
            System.out.println(l.getShape());
        });
    }

}
